package com.pet.shop.controller.product;

import com.alibaba.fastjson.JSONObject;
import com.pet.shop.entity.product.Product;
import com.pet.shop.service.product.IProductService;
import com.pet.shop.utils.ApiResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/product")
public class ProductApiController {

    @Autowired
    private IProductService productService;
    @Value("${fileViewServer}")
    private String fileViewServer;
    @Value("${fileDefaultAdvert}")
    private String fileDefaultAdvert;

    /**
     * shwo
     * @return
     */
    @RequestMapping("listType/{typeId}")
    public Map<String, Object> list(@PathVariable("typeId") Integer typeId){
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("typeId", typeId);
        paramMap.put("status", 1);
        List<Product> productList = productService.queryProductInfoList(paramMap);
        if(productList == null) productList = new ArrayList<>();

        List<JSONObject> results = productList.stream().map(product -> {
            JSONObject json = new JSONObject();
            json.put("id", product.getId());
            json.put("name", product.getName());
            json.put("picUrl", StringUtils.isEmpty(product.getPicUrl())?fileDefaultAdvert: fileViewServer + product.getPicUrl());
            json.put("price", product.getPrice());
            return json;
        }).collect(Collectors.toList());

        return ApiResultUtil.success_data(results);
    }

}
